package com.zhouxin.customview.view

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import kotlin.math.min


/**
 * Copyright©
 * FileName: SquareImageView
 * Author: ZhouXin
 * Date: 2022/6/20
 * Description: 正方形ImageView
 */
class SquareImageView(context: Context, attrs: AttributeSet) : AppCompatImageView(context, attrs) {

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //getMeasuredWidth()和getMeasuredHeight()获取的是期望值
        //getWidth()和getHeight()获取的是实际值，在layout之后才能获取成功，在onMeasure里面使用通常获取的是上一次的值
        val size = min(measuredWidth, measuredHeight)
        setMeasuredDimension(size, size)
    }

    /*//虽然这样也可以达到效果，但是会出现意想不到的结果，一般不会这样做
    override fun layout(l: Int, t: Int, r: Int, b: Int) {
        val width = r - l
        val height = b - t
        val size  = min(width, height)
        super.layout(l, t, l+v, t+v)
    }*/

}